package utils

import (
	"fmt"
	"github.com/yapingcat/gomedia/go-codec"
	"io/ioutil"
	"math"

	"os"
)

//func PlayMP3(filename string) (err error) {
//	f, err := os.Open("aliyun_0.mp3")
//	if err != nil {
//		return err
//	}
//	defer f.Close()
//	d, err := mp3.NewDecoder(f)
//	if err != nil {
//		return err
//	}
//	c, ready, err := oto.NewContext(d.SampleRate(), 2, 2)
//	if err != nil {
//		return err
//	}
//	<-ready
//
//	p := c.NewPlayer(d)
//	defer p.Close()
//	p.Play()
//
//	fmt.Printf("Length: %d[bytes]\n", d.Length())
//	for {
//		time.Sleep(time.Second)
//		if !p.IsPlaying() {
//			break
//		}
//	}
//	return nil
//}

func EstimateMP3Duration(filename string) (duration int, err error) {
	f, err := os.Open(filename)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()

	mp3, _ := ioutil.ReadAll(f)
	//fmt.Println("Get Mp3 file size", len(mp3))
	frameCnt := 0
	codec.SplitMp3Frames(mp3, func(head *codec.MP3FrameHead, frame []byte) {
		frameCnt += 1
		//fmt.Println("Get mp3 Frame")
		//fmt.Printf("mp3 frame head %+v\n", head)
		//fmt.Printf("mp3 bitrate:%d,samplerate:%d,channelcount:%d\n", head.GetBitRate(), head.GetSampleRate(), head.GetChannelCount())
	})
	//fmt.Println("frameCnt:", frameCnt)

	var frameDuration float64 = 0.026
	//dtime := math.Ceil(float64(frameCnt) * frameDuration)
	dtime := math.Floor(float64(frameCnt) * frameDuration)
	return int(dtime), nil
}
